﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Text;
using System.Data.Objects.DataClasses;

using FRL.DebtChased.Extensions;

namespace FRL.DebtChased.Repository
{

	/// <summary>
	/// Extensions to the Personalization model
	/// </summary>
	public partial class Personalization
	{

		/////////////////////////////////////////////////////////////
		// Static Operations

		public static void SetBlobs(DebtChasedEntities ent, string strPagePath, byte[] userDataBlob, int iUserId)
		{

			// Look up data
			Personalization pz = (
				from p in ent.Personalizations
				where (p.UserId == iUserId) && (p.PageUrl == strPagePath)
				select p
			).FirstOrDefault();
			if (pz == null)
			{

				// Add a new record
				pz = Personalization.CreatePersonalization(0,iUserId,strPagePath);
				pz.UserData = userDataBlob;
				ent.Personalizations.AddObject(pz);

				// Save changes to database
				ent.SaveChanges();

			}
			else
			{

				// If the data has changed...
				if (!userDataBlob.Compare(pz.UserData))
				{

					// Update record
					pz.UserData = userDataBlob;

					// Save changes to database
					ent.SaveChanges();

				}

			}

		}

		public static void GetBlobs(DebtChasedEntities ent, string strPagePath, ref byte[] sharedDataBlob, ref byte[] userDataBlob, int iUserId)
		{

			// Look up data
			Personalization pz = (
				from p in ent.Personalizations
				where (p.UserId == iUserId) && (p.PageUrl == strPagePath)
				select p
			).FirstOrDefault();

			// If data found...
			if (pz != null)
			{

				// Update function parameters
				sharedDataBlob = pz.SharedData;
				userDataBlob = pz.UserData;

			}

		}

		public static void ResetBlobs(DebtChasedEntities ent, string strPagePath, int iUserId)
		{

			// Look up data
			Personalization pz = (
				from p in ent.Personalizations
				where (p.UserId == iUserId) && (p.PageUrl == strPagePath)
				select p
			).FirstOrDefault();
			if (pz != null)
			{

				// If the data has changed...
				if (
					(pz.UserData != null)
					||
					(pz.SharedData != null)
				)
				{

					// Update record
					pz.UserData = null;
					pz.SharedData = null;

					// Save changes to database
					ent.SaveChanges();

				}

			}

		}

	}

}
